import { route } from 'quasar/wrappers';
import {
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';
import routes from './routes';
import { LoadingBar } from 'quasar';
import type { RouteLocationNormalized } from 'vue-router';
import { useAuthStore, useLayoutStore } from 'src/stores/layout-store';

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default route(function (/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : process.env.VUE_ROUTER_MODE === 'history'
    ? createWebHistory
    : createWebHashHistory;

  const Router = createRouter({
    scrollBehavior: () => ({ top: 0, left: 0 }),
    routes,

    // Leave this as is and make changes in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    history: createHistory(
      process.env.MODE === 'ssr' ? void 0 : process.env.VUE_ROUTER_BASE
    ),
  });
  /* 这个里面无需鉴权 */
  const notCheckPath = ['/login', '/search'];

  Router.beforeEach(
    (to: RouteLocationNormalized, form: RouteLocationNormalized, next) => {
      LoadingBar.start();

      const auth = useAuthStore();
      const layout = useLayoutStore();
      if (notCheckPath.indexOf(to.fullPath) > -1) {
        next();
      } else {
        // 不存在则跳转到登录页面
        if (auth.token) {
          if (to.fullPath === '/') {
            // 切换面包屑
            layout.crumbsList = [layout.mainPage];
          } else {
            const item = to.query.url
              ? layout.menuPathMap.get(to.query.url as string)
              : layout.menuPathMap.get(to.fullPath);
            if (item) {
              // 切换面包屑
              layout.crumbsList = layout.findP(item);
              // 增加Tab栏
              if (layout.tabList.filter((i) => i.id === item.id).length === 0) {
                layout.tabList.push(item);
              }
            }
          }
          next();
        } else {
          next({ path: '/login' });
        }
      }
    }
  );

  Router.afterEach(() => {
    LoadingBar.stop();
    LoadingBar.stop();
  });

  return Router;
});
